<template>
<!-- eslint-disable -->
<div id="main-content" class="buy-box">
  <Scroll ref="tabScroll" :scroll-bars="false" scroll-direction="X" class="tab">
    <div slot="body" ref="tabList" class="tab-list">
      <div v-for="(filter, index) in filterList" @click="selectFilter(filter)" :key="index" :class="['tab-item',  filter.status === currentFilterStatus ? 'active' : null]">
        <span>{{filter.name}}</span>
        <span v-if="filter.num > 0" class="badge">{{filter.num}}</span>
      </div>
    </div>
  </Scroll>
  <Scroll class="release-list" v-for="(filter, index) in filterList" :ref="`scroll_${filter.alias}`" v-show="filter.alias === currentFilterStatusAlias" :key="`${index}-${index}`" @infiniteScroll="getMyBuy">
    <div  class="release-item" v-for="(item, i) in currentBuyList" :key="i">
      <router-link class="item-tit" tag="div" :to="{path: `/goods/orderDetails/${item.mallSellOrderId}?postage=${item.postage}&sellPrice=${item.sellPrice}&time=${item.orderStatus === 1 ? item.sellTime : (item.sendTime || 0)}`}">
        <div class="pic">
          <img class="picItem" :src="item.productsUrl | ImgFilter" alt="IMG">
        </div>
        <div class="goods-info">
          <div class="title">
            <span>{{item.productsName}}</span>
          </div>
          <div class="money">
            <span>￥{{item.sellPrice}}</span>
          </div>
          <div class="state">
            <span>{{item.orderStatus | orderStatusFilter}}</span>
            <CountDown
              :intervalId="`${filter.alias}-${i}`"
              v-if="+item.orderStatus === 1 || +item.orderStatus === 5 "
              :totalSeconds="+item.orderStatus === 1 ? item.sellTime : item.sendTime"
              :timeType="item.orderStatus === 1 ? 2 : 1"
              @endTime="handleTimeDownEnd(item)"
            >
              <span>{{+item.orderStatus === 1 ? "内完成支付" : (+item.orderStatus === 5 ? "后将自动收货" : "")}}</span>
            </CountDown>
          </div>
        </div>
        <div class="arrow">
          <i class="icon-arrow"></i>
        </div>
      </router-link>
      <div class="edit" v-if="item.orderStatus == 1 || item.orderStatus == 5">
        <button class="edit-btn" v-if="+item.orderStatus === 1" @click="handlePayment(item)">付款</button>
        <button class="edit-btn" v-if="+item.orderStatus === 5" @click="handleOpenConfirmMoney(item)">确认收货</button>
        <button class="edit-btn" v-if="+item.orderStatus === 1" @click="handleCancelPayment(item)">取消</button>
      </div>
    </div>
    <div class="noList" v-if="emptyList">您暂无买到的商品，快去买一个吧！</div>
  </Scroll>
  <Popups :isShow.sync="isPopup_cancel" title="取消订单">
      <div  class="cancel-info info-center" slot="body">
        <span>确定要取消订单吗？</span>
      </div>
      <div slot="footer" class="pop-footer-btns">
        <button class="pop-footer-cancel" @click="closePopAll" >再想想</button>
        <button class="pop-footer-sub" @click="handleEnsureClose">确定</button>
      </div>
    </Popups>
    <Popups :isShow.sync="isPopup_confirmMoney" title="确认收货">
      <div  class="cancel-info" slot="body">
        <span>您确认收货后货款将立即打款给卖家，请确认您已收到商品</span>
      </div>
      <div slot="footer" class="pop-footer-btns">
        <button class="pop-footer-cancel" @click="closePopAll" >取消</button>
        <button class="pop-footer-sub" @click="handleConfirmMoney" >确定</button>
      </div>
    </Popups>
    <Popups :isShow.sync="isPopup_payment" :VClose="false" :delayTime="popTip.delayTime || 0" :title="popTip.title">
      <div  :class="['cancel-info', popTip.type === 1 ? 'info-center' : null]" slot="body">
        <span v-html="popTip.info">
        </span>
      </div>
      <div slot="footer" class="pop-footer-btns">
        <button class="pop-footer-close" @click="goMyBuy" >确定</button>
      </div>
    </Popups>
</div>
</template>

<script>
import { Popups } from "~/popOut/";
import CountDown from "~/countDown";
import { Scroll } from "~/vScroll";
import Ajax from "@/mixins/ajax";

// 获取我买到的列表
const getMyBuyUrl = "/card-service-web/resell/myBuy";
// 创建订单
// const createOrders = "/card-service-web/resell/createOrders";
// 取消订单
const setCloseBuyUrl = "/card-service-web/resell/closeBuy";
// 确认收货
const confirmMoneyUrl = "/card-service-web/resell/confirmMoney";
// 支付宝支付接口
const alipayUrl = "/card-service-web/alipay/alipay";
// 我买到的记录新街口
const getRecordByCondition = "/card-service-web/resell/getRecordByCondition";

const successPayment = {
  title: "",
  type: 1,
  info: "购买成功"
};
const filters = [
  {
    name: "全部",
    status: 0,
    alias: "all"
  },
  {
    name: "待付款",
    status: 1,
    num: 0,
    alias: "payment"
  },
  {
    name: "待发货",
    status: 4,
    num: 0,
    alias: "sendGoods"
  },
  {
    name: "待收货",
    status: 5,
    num: 0,
    alias: "stayGoods"
  },
  {
    name: "已完成",
    status: 7,
    alias: "completed"
  },
  {
    name: "已关闭",
    status: 3,
    alias: "close"
  }
];

export default {
  name: "MyBuy",
  mixins: [Ajax],
  components: {
    Popups,
    CountDown,
    Scroll
  },
  filters: {
    orderStatusFilter(value) {
      let state = "";
      switch (value) {
        case 1:
          state = "待付款";
          break;
        case 2:
          state = "已取消";
          break;
        case 3:
          state = "已关闭";
          break;
        case 4:
          state = "待发货";
          break;
        case 5:
          state = "待收货";
          break;
        case 7:
          state = "已完成";
          break;
        default:
          break;
      }
      return state;
    }
  },
  data() {
    return {
      busy: false,
      // pop窗口状态
      isPopup_cancel: false,
      // 确认收货弹框状态
      isPopup_confirmMoney: false,
      // 我买到的列表
      myBuyList: {},
      // 当前买到的列表
      currentBuyList: [],
      // 当前买家ID
      currentBuyUserId: 0,
      // 当前卖家ID
      currentSellUserId: 0,
      // 当前商品订单ID
      currentOrderId: 0,
      // 转卖ID
      currentMallResellId: 0,
      // 订单ID
      mallSellOrderId: 0,
      // 列表为空？
      emptyList: false,
      isPopup_payment: false,
      // 支付成功提示
      popTip: successPayment,
      // 筛选列表
      filterList: filters,
      // 当前筛选状态
      currentFilterStatus: 0,
      // 当前筛选状态的别名
      currentFilterStatusAlias: "all"
    };
  },
  mounted() {
    // 支付成功判断
    const { totalAmout } = this.$route.query;
    if (totalAmout) {
      this.isPopup_payment = true;
    }
    // 第一次请求
    this.firstAjax = true;
    this.getMyBuy();
    // 更新IScroll尺寸
    this.$nextTick(() => {
      const tabListHeight =
        parseInt(this.getStyle(this.$refs.tabList, "height"), 10) + 1;
      this.$refs.tabScroll.$el.style.height = `${tabListHeight}px`;
      const tabScrollHeight = parseInt(
        this.getStyle(this.$refs.tabScroll.$el, "height"),
        10
      );
      const mainHeight =
        this.windowHeight - (this.headerElHeight + tabScrollHeight);
      filters.forEach(item => {
        this.$refs[
          `scroll_${item.alias}`
        ][0].$el.style.height = `${mainHeight}px`;
      });

      this.$refs.tabScroll.refresh();
    });
  },
  methods: {
    /**
     * 刷新当前页
     */
    goMyBuy() {
      this.isPopup_payment = false;
      this.$router.replace({ name: "myBuy" });
    },
    /**
     * 定时器结束
     */
    handleTimeDownEnd(item) {
      /* eslint-disable */
      // 倒计时结束更新徽章
      this.filterList.forEach((key, index) => {
        if (key.status === item.orderStatus) {
          --this.filterList[index].num;
        }
        if (key.status === item.orderStatus) {
          --this.filterList[index].num;
        }
        if (key.status === item.orderStatus) {
          --this.filterList[index].num ;
        }
      });
      // 更新列表
      this.getMyBuy();


      // // 如果当前商品收货时间结束则改变状态为已完成
      // +item.orderStatus === 5 && (item.orderStatus = 7);
      // // 如果当前商品付款时间结束则改变状态为已关闭
      // +item.orderStatus === 1 && (item.orderStatus = 3);
    },
    /**
     * 关闭所有pop
     */
    closePopAll() {
      this.isPopup_cancel = false;
      this.isPopup_confirmMoney = false;
    },
    /**
     * 获取我买到的商品列表
     */
    getMyBuy(status) {
      const url =
        this.currentFilterStatusAlias === "all"
          ? getMyBuyUrl
          : getRecordByCondition;
      ((status, currentFilterStatusAlias) => {
        this.post(url, {
          /* eslint-disable */
          pageNo: ++this.currentPageNo,
          pageSize: 10,
          // 当前查询的商品状态
          orderStatus: status,
          // 固定值 1：我买到的 2： 我发布的
          condition: 1
        }).then(body => {
          // 如果返回列表为空则不需要更新列表
          if (body.execDatas.length === 0) {
            --this.currentPageNo;
          }
          // 如果为第一页则不需要concat
          if (this.currentPageNo <= 1) {
            this.currentBuyList = body.execDatas;
          } else {
            this.currentBuyList = (this.currentBuyList || []).concat(
              body.execDatas
            );
          }
          // 设置当前渲染列表
          // 如果调用的是全部的接口则更新徽章数据
          if (currentFilterStatusAlias === "all") {
            // 更新徽章数量
            const { waitPayCount, waitPushCount, waitReceivingCount } =
              body.execData || {};
            // 如果是第一次请求
            if (this.firstAjax) {
              this.firstAjax = false;
              // 当前过滤item
              let filter;
              // 如果待付款列表有数据则切换为待付款
              if (waitPayCount > 0) {
                filter = this.filterList.filter(item => {
                  return item.status === 1;
                });
              } else if (waitPushCount > 0) {
                // 如果待付款列表没有数据待发货列表有数据则切换为待发货
                filter = this.filterList.filter(item => {
                  return item.status === 4;
                });
              } else if (waitPushCount > 0) {
                // 如果待付款、待发货列表没有数据待收货列表有数据则切换为待收货
                filter = this.filterList.filter(item => {
                  return item.status === 5;
                });
              }
              // 切换为当前筛选
              filter && this.selectFilter(filter[0]);
            }
            this.filterList.forEach((item, index) => {
              if (waitPayCount > 0 && item.status === 1) {
                this.filterList[index].num = waitPayCount;
              }
              if (waitPushCount > 0 && item.status === 4) {
                this.filterList[index].num = waitPushCount;
              }
              if (waitReceivingCount > 0 && item.status === 5) {
                this.filterList[index].num = waitReceivingCount;
              }
            });
          }

          // 更新IScroll尺寸
          this.$nextTick(() => {
            this.$refs[`scroll_${currentFilterStatusAlias}`][0].refresh();
          });

          if ((this.currentBuyList || []).length === 0) {
            this.emptyList = true;
          } else {
            this.emptyList = false;
          }
        });
      })(status || this.currentFilterStatus, this.currentFilterStatusAlias);
    },
    /**
     * 处理取消购买订单
     * @param {Object} item 商品详情
     */
    handleCancelPayment(item) {
      // 暂存当前选中买家ID
      this.currentBuyUserId = item.buyUserId;
      // 暂存当前选中的卖家ID
      this.currentSellUserId = item.sellUserId;
      // 暂存当前选中的商品订单ID
      this.currentOrderId = item.mallResellId;
      // 暂存当前选中的商品转卖订单ID
      this.mallSellOrderId = item.mallSellOrderId;

      this.isPopup_cancel = true;
    },
    /**
     * 弹出确认收货弹框
     */
    handleOpenConfirmMoney(item) {
      // 暂存当前选中的商品订单ID
      this.currentOrderId = item.mallSellOrderId;
      this.isPopup_confirmMoney = true;
    },
    /**
     * 处理付款
     * @param {Object} item 商品详情
     */
    handlePayment(item) {
      // 跳转到确认订单页
      // 并且传递卖家ID 和 转卖ID
      // this.$router.push(
      //   `/goods/MakeSureOrder?mallResllId=${item.mallResellId}&sellUserId=${
      //     item.mallSellOrderId
      //   }`
      // );
      //没有生成订单步骤则不需要弹出等待窗口
      // const loading = {
      //   isPrompt: true,
      //   isCloseEl: false,
      //   isConfirm: false,
      //   title: "",
      //   info: "正在努力跳转到支付宝请稍等",
      //   isMaskDown: false,
      //   textAlign: "center"
      // };
      // // 弹出等待窗口
      // this.$emit("onPrompt", loading);
      const {
        // 转卖订单ID
        mallSellOrderId,
        // 商品名称
        productsName,
        // 转卖价格
        sellPrice,
        // 邮费
        postage
      } = item;
      const totalAmout = +sellPrice + +postage;
      const href = `${alipayUrl}?body=${productsName}&outTradeNo=${mallSellOrderId}&subject=${productsName}&totalAmout=${totalAmout}&returnUrl=${encodeURIComponent(
        `${window.location.href}?totalAmout=${totalAmout}`
      )}`;
      location.href = href;
    },
    /**
     * 确定取消订单
     */
    handleEnsureClose() {
      const { currentBuyUserId, mallSellOrderId } = this;
      // 发送取消订单请求
      this.post(setCloseBuyUrl, {
        buyUserId: currentBuyUserId,
        id: mallSellOrderId
      }).then(body => {
        if (+body.execErrCode === 200) {
          this.currentBuyList = this.currentBuyList.filter(item => {
            return item.mallSellOrderId !== mallSellOrderId;
          });
          // 当前筛选数量-1
          this.filterList.forEach((item, index) => {
            if (item.alias === this.currentFilterStatusAlias) {
              --this.filterList[index].num;
            }
          });
        }
        this.isPopup_cancel = false;
      });
    },
    /**
     * 确认收货
     */
    handleConfirmMoney() {
      const { currentOrderId } = this;
      // 发送确认订单请求
      this.post(confirmMoneyUrl, {
        id: currentOrderId
      }).then(body => {
        // 关闭确认框
        this.isPopup_confirmMoney = false;
        // 初始化当前页码
        this.currentPageNo = 0;
        // 刷新当期页
        this.getMyBuy();
      });
    },
    /**
     * 选择筛选对象
     */
    selectFilter(filter) {
      // 初始化当前页码
      this.currentPageNo = 0;
      // 保存当前的条件状态码
      this.currentFilterStatus = filter.status;
      // 保存当前条件别名
      this.currentFilterStatusAlias = filter.alias;
      // 更新IScroll尺寸
      this.$nextTick(() => {
        this.$refs[`scroll_${filter.alias}`][0].refresh();
      });
      this.getMyBuy(filter.status);
    }
  }
};
</script>

<style scoped>
.noList {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 2.6rem;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  padding-top: 3rem;
  color: #888888;
}
.buy-box {
  width: auto;
  background: #fff;
}
.release-list {
  background: #f5f5f4;
}
.tab {
  height: 1.1rem;
}
.tab-list {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: nowrap;
  background: #fff;
  font-size: 0.45rem;
  box-shadow: 0rem 0.01rem 0rem 0rem #e1e1e1;
  padding: 0 0.6rem;
  color: #666;
  border-bottom: 0.01rem solid #e1e1e1;
}
.tab-list .tab-item:first-child {
  margin-left: 0;
}
.tab-list .tab-item {
  display: inline-block;
  white-space: nowrap;
  margin-left: 0.8rem;
  padding: 0.26rem 0 0.29rem;
  position: relative;
}
.tab-list .tab-item.active {
  color: #d11463;
  border-bottom: 0.06rem solid #d11463;
}
.tab-list .badge {
  display: inline-block;
  position: absolute;
  top: 0.1rem;
  right: -0.4rem;
  background-color: #d11463;
  font-size: 0.33rem;
  color: #fff;
  min-width: 0.25rem;
  padding: 0.05rem 0.09rem;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  border-radius: 200px;
}
.release-item {
  background-color: #fff;
  margin-bottom: 0.45rem;
}
.release-item .item-tit {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  padding: 0.46rem 0 0.45rem;
}
.release-item .pic {
  width: 1.8rem;
  height: 1.8rem;
  margin-left: 0.47rem;
  background-color: #8e8e8e;
  overflow: hidden;
}
.release-item .pic .picItem {
  width: 1.8rem;
  height: 1.8rem;
}
.goods-info {
  -webkit-flex-grow: 1;
  flex-grow: 1;
  padding: 0 0.2rem;
}
.goods-info .title {
  margin-bottom: 0.33rem;
  font-size: 0.42rem;
  letter-spacing: 0rem;
  color: #000000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 6rem;
}
.goods-info .money {
  font-size: 0.42rem;
  margin-bottom: 0.35rem;
  line-height: 0.36rem;
  letter-spacing: 0rem;
  color: #000000;
}
.goods-info .state {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  font-size: 0.36rem;
  line-height: 0.36rem;
  letter-spacing: 0rem;
  color: #d11463;
}
.item-tit .arrow {
  -webkit-align-self: center;
  align-self: center;
  text-align: right;
  margin-right: 0.3rem;
}
.item-tit .arrow .icon-arrow {
  display: inline-block;
  width: 0.24rem;
  height: 0.43rem;
  background: url("../../assets/img/arrow.png") no-repeat;
  background-size: 100%;
}
.edit {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row-reverse;
  flex-direction: row-reverse;
  height: 1.5rem;
  -webkit-align-items: center;
  align-items: center;
  padding-right: 0.48rem;
  border-top: 0.01rem solid #e1e1e1;
}
.edit .edit-btn {
  width: 2.19rem;
  height: 0.9rem;
  background-color: #ffffff;
  border: solid 1px #000000;
  border-radius: 0.1rem;
}
.edit .edit-btn:nth-child(2) {
  margin-right: 0.6rem;
}
/* 弹框按钮公共部分 */
.cancel-info {
  margin-top: 0.63rem;
  font-size: 0.42rem;
}
.pop-footer-btns {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-justify-content: space-around;
  justify-content: space-around;
}
.pop-footer-cancel {
  width: 2.71rem;
  height: 1.08rem;
  background-color: #5062a6;
  border-radius: 2rem;
  color: #fff;
  font-size: 0.54rem;
}
.pop-footer-sub {
  width: 2.71rem;
  height: 1.08rem;
  background-color: #d11463;
  border-radius: 2rem;
  color: #fff;
  font-size: 0.54rem;
}
.cancel-info {
  margin-top: 0.62rem;
  font-size: 0.42rem;
  text-align: left;
}
.info-center {
  text-align: center;
}
.pop-footer-btns .pop-footer-close {
  width: 5.01rem;
  height: 1.08rem;
  background-color: #d11463;
  border-radius: 2rem;
  color: #fff;
  font-size: 0.54rem;
}
</style>

